<?php
/**
 * Smarty wrapper
 * Last update May 1st 2009
 * @author Urban Soban
 * @package Smarty
 * @copyright 2009 Smarty.com
 */

class SmartyController extends ApplicationController {
	protected $AppName = "smarty";
	
	/**
	 * Creates smarty environment
	 */
	function init(){
		// Make sure smarty is initialized only once
		$Initialized = ApplicationRegistry::getInstance()->get("smarty_init");
		
		if($Initialized == 1){
			return $this;
		}
		else {
			ApplicationRegistry::getInstance()->set("smarty_init", 1);
		}
		
		// Get template name
		$TemplateName = SystemRegistry::getInstance()->get("template");
		
		// Get environment varibles
		$FMSConfig = Core::$FMSConfig;
		$EnvironmentVaribles = $FMSConfig->getType("environment");
		
		// Set Smarty settings
		$SmartySettingsDir = dirname(__FILE__)."/../../smdir/";
		$Smarty = new Smarty();
		
		$Smarty->compile_dir = $SmartySettingsDir."templates_c";
		$Smarty->cache_dir = $SmartySettingsDir."cache";
		$Smarty->config_dir = $SmartySettingsDir."configs";
		$Smarty->template_dir = dirname(__FILE__)."/../../theme/".$TemplateName;
		
		// Set environment varibles
		$SmartyEnv = array();
		
		foreach ($EnvironmentVaribles as $ENVName => $ENValue){
			$SmartyEnv[$ENVName] = $ENValue["value"];
		}
		
		// Save environment varibles to smarty
		$Smarty->assign("env", $SmartyEnv);
		
		
		// Register custom smarty functions
		$Smarty->register_function("run_app","run_application");
		
		// Save smarty to ApplicationRegistry
		ApplicationRegistry::getInstance()->set("Smarty", $Smarty);
		
		$this->startOperations();
	}
	
	/**
	 * Returns static Smarty object 
	 *
	 * @return Smarty
	 */
	function getSmarty(){
		$Static_Smarty = ApplicationRegistry::getInstance()->get("Smarty");
		
		if($Static_Smarty != false){
			return $Static_Smarty;
		}
		
		return false;
	}
	
	function startOperations(){
		$Smarty = $this->getSmarty();
		
		$AccountRequest = new Request("account", "getAccount");
		$AccountResult = RequestHandler::interrupt($AccountRequest, 1);
		
		$Smarty->assign("UserAccount", $AccountResult);
	}
	
	/**
	 * Adds html tag to <head>
	 *
	 * @param string $tag
	 */
	function addHeadTag($tag){
		if(trim($tag) != ""){
			$smarty = $this->getSmarty();
			$head_tag = $smarty->get_template_vars("html_head_tags");
			$head_tag .= "\n\t".$tag;
			$smarty->assign("html_head_tags", $head_tag);
		}
	}

}

?>